from fdfs_client.client import Fdfs_client
from rest_framework import serializers

from apps.goods.models import  SKUImage, SKU


class ImageSerializers(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = ["id", "sku", "image"]

    def validate(self, attrs):

        image_obj = attrs.get('image')  # 图片文件对象
        # (1)、在校验过程中，手动从文件对象中读取图片数据，上传fdfs
        conn = Fdfs_client('./meiduo_mall/settings/client.conf')
        res = conn.upload_by_buffer(image_obj.read())
        if res is None:
            raise serializers.ValidationError("fdfs上传失败！")
        # (2)、再把fdfs返回的文件标示(文件id)作为有效数据中image字段的值
        attrs['image'] = res['Remote file_id']

        return attrs



class SKUImageSerializers(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields =["id", "name"]





